package com.example.myapplication.module_notification;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;

import com.example.myapplication.data.Notification;
import com.example.myapplication.databinding.ActivitySearchResultBinding;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;

import com.example.myapplication.R;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class SearchResult extends AppCompatActivity {

    private final int MSG_SEARCH_DATA = 1;
    private final int MSG_NO_DATA = 2;
    List<Notification> search_result = new ArrayList<>();
    ListView listView;
    Handler handler;
    private ActivitySearchResultBinding binding;

    @Override

    @SuppressLint("HandlerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
        Transition fade_in = TransitionInflater.from(this).inflateTransition(R.transition.fade_in);
        getWindow().setEnterTransition(fade_in);
        getWindow().setExitTransition(fade_in);

        binding = ActivitySearchResultBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        listView = binding.searchRet;
        binding.searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                Log.d(TAG, "afterTextChanged: ");
                getSearchData();
            }
        });
        Context c = this;
        this.handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_SEARCH_DATA:

                        search_result = (List<Notification>)msg.obj;
                        listView.setAdapter(new NotificationsAdapter(c,search_result));
                        break;
                    case MSG_NO_DATA:
                        //回退
                        break;
                }
            }
        };
    }

    private void getSearchData(){
        String s = binding.searchInput.getText().toString();
        if ("".equals(s)){
            return;
        }
        String url = getString(R.string.httpPrefix) + "/searchNotification?title=" +s + "&keyword="+s;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    //创建OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建Request// 注意，调试时候模拟器访问电脑用10.0.2.2....

                    Request request = new Request.Builder()
                            .url(url)//访问连接
                            .get()
                            .build();
                    //创建Call对象
                    Call call = client.newCall(request);

                    Gson gson = new Gson();
                    //通过execute()方法获得请求响应的Response对象
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        ResponseBody body = response.body();
                        String string = body.string();
                        Log.e(TAG, "search: " + string);
                        List<Notification> list = gson.fromJson(string, new TypeToken<List<Notification>>() {
                        }.getType());
                        if(list!=null){
                            //可以正常反序列化//
                            for (int i = list.size() - 1; i >= 0; i--) {
                                Log.e(TAG, "search--: " + list.get(i));
                            }
                            Message message = new Message();
                            message.what = MSG_SEARCH_DATA;
                            message.obj = list;
                            handler.sendMessage(message);
                        }else{
                            Message message = new Message();
                            message.what = MSG_NO_DATA;
                            handler.sendMessage(message);
                        }
                    }
                } catch (Exception e) {
                    Log.d(TAG, "run: errrrrrrrrrrrrrrrrrrr");
                    e.printStackTrace();
                }
            }
        }).start();

    }

}